<?php

namespace app\api\controller;

use app\common\controller\Api;

/**
 * 收货地址
 */
class Address extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [''];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    //我的收货地址
    public function getmyaddress(){
        $user = $this->auth->getUser();
        $list = db('address')->where(['user_id'=>$user->id])->order('isdefault desc')->select();
        $this->success('ok',$list);
    }
    //添加收货地址
    public function addaddress(){
        $user = $this->auth->getUser();
        $name = input('name','');
        $mobile = input('mobile','');
        $city = input('city','');
        $address = input('address','');
        $isdefault = input('isdefault','0');
        if(!$name || !$mobile || !$city || !$address){
            $this->error('请完善信息');
        }
        if($isdefault==1){
            db('address')->where(['user_id'=>$user->id])->update(['isdefault'=>0]);
        }
        $data['user_id'] = $user->id;
        $data['name'] = $name;
        $data['mobile'] = $mobile;
        $data['city'] = $city;
        $data['address'] = $address;
        $data['isdefault'] = $isdefault;
        $data['createtime'] = time();
        $res = db('address')->insert($data);
        if($res){
            $this->success('添加成功');
        }else{
            $this->error('添加失败');
        }
    }
    //修改收货地址
    public function editaddress(){
        $user = $this->auth->getUser();
        $id = input('id','');
        if(!$id){
            $this->error('请选择地址');
        }
        $name = input('name','');
        $mobile = input('mobile','');
        $city = input('city','');
        $address = input('address','');
        $isdefault = input('isdefault','0');
        if(!$name || !$mobile || !$city || !$address){
            $this->error('请完善信息');
        }
        if($isdefault==1){
            db('address')->where(['user_id'=>$user->id])->update(['isdefault'=>0]);
        }
        $data['user_id'] = $user->id;
        $data['name'] = $name;
        $data['mobile'] = $mobile;
        $data['city'] = $city;
        $data['address'] = $address;
        $data['isdefault'] = $isdefault;
        // $data['createtime'] = time();
        $res = db('address')->where(['id'=>$id])->update($data);
        if($res){
            $this->success('修改成功');
        }else{
            $this->error('暂无修改');
        }
    }
    //删除收货地址
    public function deladdress(){
        $id = input('id','');
        if(!$id){
            $this->error('请选择地址');
        }
        $res = db('address')->where(['id'=>$id])->delete();
        if($res){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }
}
